import { Button, List, Toast } from 'antd-mobile'
import { useAppDispatch, useAppSelector } from '../../hooks/redux'
import { resetUser } from '../../store/slices/userSlice'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.css'
import { useEffect, useState } from 'react'
import { fetchUserDetail } from '../../services/api'
import type { UserDetail } from '../../types/api'

export default function Mine() {
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const nickname = useAppSelector(s => s.user.nickname) || '秋bling'
  const [profile, setProfile] = useState<UserDetail | null>(null)
  const [auth, setAuth] = useState<any>(null)

  useEffect(() => {
    try {
      const raw = typeof window !== 'undefined' ? window.localStorage?.getItem('authInfo') : null
      if (raw) setAuth(JSON.parse(raw))
    } catch {}
    const uid = (() => {
      try {
        const raw = typeof window !== 'undefined' ? window.localStorage?.getItem('authInfo') : null
        return raw ? JSON.parse(raw)?.userId : undefined
      } catch {
        return undefined
      }
    })()
    if (uid != null) {
      fetchUserDetail(uid)
        .then(setProfile)
        .catch(() => null)
    }
  }, [])

  const handleLogout = () => {
    dispatch(resetUser())
    try {
      window.localStorage && window.localStorage.removeItem('authInfo')
    } catch {}
    Toast.show({ icon: 'success', content: '已退出登录' })
    navigate('/login', { replace: true })
  }

  // shortcuts 已暂时移除，如需入口可在此恢复

  return (
    <div>
      <div className={styles['mine-header']}>
        <div className={styles['mine-profile']}>
          <div className={styles['mine-avatar']}>😊</div>
          <div className={styles['mine-nickname']}>
            {auth?.userName || auth?.account || profile?.realName || profile?.name || nickname}
          </div>
        </div>
      </div>

      <div className={styles['mine-list']}>
        <List>
          <List.Item onClick={() => Toast.show('开发中')} arrow>
            我的消息
          </List.Item>
          <List.Item onClick={() => Toast.show('开发中')} arrow>
            关于我们
          </List.Item>
          <List.Item extra="V2.0" arrow onClick={() => Toast.show('已是最新版本')}>
            版本信息
          </List.Item>
        </List>
      </div>

      <div className={styles['mine-agreements']}>
        <span>《用户协议》</span>
        <span style={{ margin: '0 6px' }}>|</span>
        <span>《隐私政策》</span>
      </div>

      <div className={styles['mine-logout']}>
        <Button
          block
          size="large"
          style={{
            border: 'none',
            color: '#fff',
            background: 'linear-gradient(135deg, #36a6ff 0%, #1677ff 100%)',
          }}
          onClick={handleLogout}
        >
          退出登录
        </Button>
      </div>
    </div>
  )
}
